<template>
  <div class="todoapp">
    <!-- 自定义事件add -->
    <TodoHeader :list="list" @add="add"></TodoHeader>
    <!-- 把list 数据传过去 -->
    <!-- 自定义删除事件 -->
    <TodoMain @odd="odd" :list="calculate"></TodoMain>
    <TodoFooter
      @qingchu="qingchu"
      @screen="screen"
      :list="calculate"
    ></TodoFooter>
  </div>
</template>

<script>
// 引入组件
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  name: "Toodolist4App",
  // 注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")),
      isSel: "all",
    };
  },

  mounted() {},

  methods: {
    // 接受TodoHeader子组件传来的数据
    add(taskname) {
      // 把子组件的数据添加到父组件list中
      this.list.push({
        id:
          this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1,
        name: taskname,
        isDone: false,
      });
    },
    odd(id) {
      // 根据传来的id找到索引删除数据
      this.list.splice(
        this.list.findIndex((item) => item.id == id),
        1
      );
    },
    screen(isSel) {
      this.isSel = isSel;
    },
    qingchu() {
      console.log(1);
      this.list = this.list.filter((item) => item.isDone == false);
    },
  },
  computed: {
    calculate() {
      if (this.isSel == "all") {
        return this.list;
      } else if (this.isSel == "yes") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list.filter((item) => item.isDone == false);
      }
    },
  },
  // 侦听器做数据缓存
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>

<style lang="scss" scoped></style>
